상속과 메서드 오버라이딩

✒️ 2025-05-19 10:25 내용 수정

Do it! 점프 투 파이썬(2017년 발행) 내용을 정리


상속

부모 클래스의 기능을 자식 클래스에서 물려받아 사용하는 것

class 클래스이름(부모클래스):
	pass
class Fruit:
    def __init__(self, name, color):
        self.name = name
        self.color = color
    def setdata(self, name, color):
        self.name = name
        self.color = color
    def printfruit(self):
        print(self.color, self.name)
    def fullname(self):
        return self.color + " " + self.name
    
class Food(Fruit):
    pass

a = Food("chicken", "red")
a.printfruit()

python_inheritance 1.png

class Fruit:
    def __init__(self, name, color):
        self.name = name
        self.color = color
    def setdata(self, name, color):
        self.name = name
        self.color = color
    def printfruit(self):
        print(self.color, self.name)
    def fullname(self):
        return self.color + " " + self.name
    
class Food(Fruit):
    def sell(self, price):
        self.price = price
        print(self.color, self.name, "for", f"${price}")

a = Food("chicken", "red")
a.printfruit()
a.sell(100)

python_inheritance 2.png


메서드 오버라이딩

부모 클래스에서 구현한 메서드를 자식 클래스에서 같은 이름으로 다시 만드는 것

class Fruit:
    def __init__(self, name, color):
        self.name = name
        self.color = color
    def setdata(self, name, color):
        self.name = name
        self.color = color
    def printfruit(self):
        print(self.color, self.name)
    def fullname(self):
        return self.color + " " + self.name
    
class Food(Fruit):
    def sell(self, price):
        self.price = price
        print(self.color, self.name, "for", f"${price}")
    # 메서드 오버라이딩
    def setdata(self, name, color, price):
        self.name = name
        self.color = color
        self.price = price

b = Food("lemon", "yellow")
b.printfruit()
b.setdata("watermelon", "green and black", "50")
print(b.name, b.color, b.price)

python_inheritance 3.png